import { Injectable } from "@nestjs/common";
import { TagEntity } from "~/modules/assess/tag/tag.entity";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { AccessTagDto } from "~/modules/assess/tag/tag.dto";
import { AccessDictService } from "../access-dict/access-dict.service";
import { AccessHouseService } from "../house/house.service";
import { HouseEntity } from "../house/house.entity";
import { AccessDictRoom } from "../access-dict/access-dict-room.entity";

@Injectable()
export class AccessTagService {
	constructor(
		@InjectRepository(TagEntity)
		private readonly tagRepository: Repository<TagEntity>,
		private readonly accessDictService: AccessDictService,
		private readonly accessHouseService: AccessHouseService
	) {
	}

	async save(accessTagDto: AccessTagDto) {
		const house: Record<string, any> = await this.accessHouseService.getHouseOriginData(accessTagDto.houseId)

		// 判断是否存在house
		if (!house) {
			throw new Error("房屋不存在")
		}

		// 循环添加标签
		return await Promise.all(accessTagDto.tags.map(async tag => {
			const tagEntity = new TagEntity()
			tagEntity.name = tag.name
			tagEntity.x = tag.x
			tagEntity.y = tag.y
			tagEntity.house = { id: accessTagDto.houseId } as any
			tagEntity.roomType = Number(tag.roomType)
			tagEntity.position = Number(tag.position)

			if (tagEntity.roomType === 0) {
				// 当前为入户门，设置户型的朝向
				this.accessHouseService.setHouseAnylysisAndSecret(accessTagDto.houseId, tagEntity.position)
			}

			const houseTypeId: number = await this.accessHouseService.getHouseTypeByHouseId(accessTagDto.houseId)
			const roomDict: AccessDictRoom = await this.accessDictService.getRoomAnalysisAndSecretDict(houseTypeId, tagEntity.roomType, tagEntity.position)

			tagEntity.realSecret = roomDict.realSecret
			tagEntity.detail = roomDict.detail

			return await this.tagRepository.save(tagEntity)
		}))
	}

	/**
	 * 根据houseId获取标签
	 * @param houseId
	 * @returns
	 */
	async getTagsByHouseId(houseId: number): Promise<TagEntity[]> {
		return await this.tagRepository.find({ where: { house: { id: houseId } } })
	}
}
